// src/pages/publishReview/index.tsx
import React, { useEffect, useMemo, useRef, useState } from 'react';
import Taro, { useDidHide, useDidShow, useUnload } from '@tarojs/taro';
import { View, Image, Text, Textarea } from '@tarojs/components';
import './index.less';
import TitleBar from '@/src/components/titleBar';
import { observer } from 'mobx-react-lite';
import store from '@/src/store';
import LoadingSpinner from '@/src/components/loadingSpinner';
import { showToast, StatusToast } from '@/src/components/statusToast';
import RelatePopup from '@/src/components/relatePopup';
import AddTopicPopup from '@/src/components/addTopicPopup';
import PhotoRecognition from '@/src/components/photoRecognition';
import {
  dynamicPublishFun,
  uploadFileFun,
} from '@/src/common/method/publishFun';
import CommonModal from '@/src/components/commonModal';
import { formatNow } from '@/src/common/method/commonFun';
import { netWorkErrorInfo } from '@/src/utils/constants';
import { getNetWorkStatus } from '@/src/common/util/util';
import { AtInput } from 'taro-ui';
const MAX_TITLE = 35;
const MAX_CONTENT = 500;
const MAX_IMAGES = 9;
let ucUserId = '';
let ucLoginPhone = '';
const PublishComment = () => {
  // 内容标题
  const [title, setTitle] = useState('');
  // 动态内容
  const [content, setContent] = useState('');
  // 显示关联产品弹窗
  const [showPopup, setShowPopup] = useState<boolean>(false);
  // 显示话题弹窗
  const [showTopicPopup, setShowTopicPopup] = useState<boolean>(false);
  // 显示识别雪茄页面
  const [showPhotoRecognition, setShowPhotoRecognition] =
    useState<boolean>(false);
  // 动态图片
  const [contentImgUrl, setContentImgUrl] = useState<string[]>([]);
  // 动态话题
  const [contentTopicList, setContentTopicList] = useState<any>([]);
  // 保存提示
  const [showSaveFlag, setShowSaveFlag] = useState<boolean>(false);
  // 等待层文字
  const [loadingText, setLoadingText] = useState<string>('');
  // 添加状态
  const [realCursorPos, setRealCursorPos] = useState(0);
  const cursorPosRef = useRef(0);
  const contentRef = useRef('');

  //  键盘高度状态
  const [keyboardHeight, setKeyboardHeight] = useState(0);
  const lastKbRef = useRef(0);

  //  判断是否需要进入短内容守护
  const needShortGuard = () => {
    return contentImgUrl.length === 0 && content.length < 150;
  };

  //  判断是否可以释放短内容守护
  const canReleaseGuard = () => {
    return contentImgUrl.length > 0 || content.length >= 200;
  };

  //  短内容守护机制：防止内容少+无图时，键盘遮挡导致无法唤起
  //  初始化时就判断是否需要守护，避免第一次聚焦时布局突变
  const [shortGuard, setShortGuard] = useState(() => needShortGuard());
  const [textareaFocus, setTextareaFocus] = useState(false);

  const { contentCigar, contentCigarCabinet } = store.publishStore;
  const { province, provinceCode, city, cityCode } = store.commonStore;
  // 是否允许在 onUnload 时保存草稿：默认 true（只为侧滑返回这种不可控场景）
  const saveOnUnloadRef = useRef(true);

  useDidShow(() => {
    Taro.onNetworkStatusChange(getNetWorkStatus);

    //  监听键盘高度变化
    // @ts-ignore
    Taro.onKeyboardHeightChange?.((res: { height: number }) => {
      const h = Math.max(0, Number(res?.height || 0));
      const opening = lastKbRef.current === 0 && h > 0;
      lastKbRef.current = h;
      setKeyboardHeight(h);

      //  键盘刚弹起时，若满足条件则进入守护
      if (opening && needShortGuard()) {
        setShortGuard(true);
      }
    });
  });

  //  页面隐藏时清理键盘监听
  useDidHide(() => {
    // @ts-ignore
    Taro.offKeyboardHeightChange?.();
  });

  // 单张上传并安全回填
  const uploadOne = async (localPath: string) => {
    const url = await uploadFileFun(localPath, 'file', {
      type: 'wine_internet_community_dynamic',
    });
    // 按"当前状态中的本地路径"查找并替换，防止索引错位
    setContentImgUrl((prev) => {
      const idx = prev.indexOf(localPath);
      if (idx === -1) return prev; // 用户可能在上传中把这张删了
      const next = [...prev];
      next[idx] = url; // 替换为服务器 URL
      return next;
    });
    return url;
  };

  // 选择图片
  const handleChooseImage = async () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    const remain = MAX_IMAGES - contentImgUrl.length;
    if (remain <= 0) {
      showToast('最多只能选 9 张图片');
      return;
    }

    const res = await Taro.chooseImage({
      count: remain,
      sizeType: ['compressed'],
      sourceType: ['camera', 'album'],
    });
    setLoadingText('上传中...');
    const newLocal = res.tempFilePaths;
    // 预览：新图在最前
    setContentImgUrl((prev) => [...prev, ...newLocal]);

    //  添加图片后延迟释放守护
    setTimeout(() => {
      setShortGuard(false);
    }, 300);

    // 并发上限
    const CONCURRENCY = 9;

    // 简单并发池
    const queue = [...newLocal];
    const results: PromiseSettledResult<string>[] = [];
    const workers = new Array(Math.min(CONCURRENCY, queue.length))
      .fill(0)
      .map(async () => {
        while (queue.length) {
          const p = queue.shift()!;
          try {
            const url = await uploadOne(p);
            results.push({
              status: 'fulfilled',
              value: url,
            } as PromiseFulfilledResult<string>);
          } catch (e: any) {
            results.push({
              status: 'rejected',
              reason: e,
            } as PromiseRejectedResult);
          }
        }
      });

    await Promise.all(workers);
    setLoadingText('');
    // 失败提示（不打断已成功的）
    if (results.some((r) => r.status === 'rejected')) {
      showToast('部分图片上传失败，可重试上传或删除');
      setLoadingText('');
    }
  };

  // iOS 左滑会触发
  useUnload(() => {
    store.commonStore.setShowTabBar(true);
    //  清理键盘监听
    // @ts-ignore
    Taro.offKeyboardHeightChange?.();

    if (!saveOnUnloadRef.current) return;
    const json = getDataFun();
    const has =
      (title && title.trim()) ||
      (content && content.trim()) ||
      (contentImgUrl?.length || 0) > 0 ||
      (contentTopicList?.length || 0) > 0 ||
      !!store.publishStore.contentCigar ||
      !!store.publishStore.contentCigarCabinet;
    if (has) {
      Taro.setStorageSync(`dynamicInfo-${ucUserId}`, JSON.stringify(json));
    }
  });

  // 删除关联雪茄
  const deleteRelateCiga = () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    store.publishStore.setContentCigar(null);
  };
  // 删除关联雪茄柜
  const deleteRelateCigaCabinet = () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    store.publishStore.setContentCigarCabinet(null);
  };

  // 删除图片点击事件
  const removeImage = (idx: number) => {
    setContentImgUrl((prev) => prev.filter((_, i) => i !== idx));
    //  删除图片后重新评估守护
    setTimeout(() => {
      if (needShortGuard()) {
        setShortGuard(true);
      }
    }, 100);
  };

  // 删除话题点击事件
  const deleteTopic = (id: any) => {
    setContentTopicList((prev: any) => prev.filter((t: any) => t.id !== id));
  };

  // 点击拍照识别的返回事件
  const onBackClickFun = () => {
    setShowPhotoRecognition(false);
  };

  // 返回点击事件
  const backClickFun = () => {
    store.commonStore.setShowTabBar(true);
    if (content.length > 0 || title.length > 0 || contentImgUrl.length > 0) {
      setShowSaveFlag(true);
    } else {
      saveOnUnloadRef.current = false;
      Taro.navigateBack();
    }
  };

  // 组成提交信息
  const getDataFun = () => {
    return {
      title,
      content,
      contentImgUrl,
      contentTopicList,
      contentCigar,
      contentCigarCabinet,
    };
  };

  // 发布按钮点击事件
  const handlePublish = () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (!title.trim()) {
      showToast('请添加标题', 'error', 2);
      return;
    } else if (!content.trim()) {
      showToast('请添加正文', 'error', 2);
      return;
    } else if (contentImgUrl.length === 0) {
      showToast('请添加图片', 'error', 2);
      return;
    }
    setLoadingText('正在发布...');
    const json = getDataFun();
    const submitTime = formatNow();
    const params = {
      ucUserId,
      ucLoginPhone,
      province,
      provinceCode,
      city,
      cityCode,
      submitTime,
      ...json,
      contentKind: 'CIGAR',
    };
    dynamicPublishFun(params)
      .then((res: any) => {
        setLoadingText('');
        if (res.code === '0') {
          setTimeout(() => {
            // 发布成功之后删除保存的草稿
            Taro.removeStorageSync(`dynamicInfo-${ucUserId}`);
            saveOnUnloadRef.current = false;
            Taro.navigateBack();
            deleteRelateCiga();
            deleteRelateCigaCabinet();
            store.commonStore.setShowTabBar(true);
          }, 3000);
          showToast('发布成功', 'success', 3);
        } else {
          showToast('发布失败', 'error', 3);
        }
      })
      .catch(() => {
        setLoadingText('');
      });
  };

  // 保存草稿
  const okClickFun = () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    const json = getDataFun();
    Taro.setStorageSync(`dynamicInfo-${ucUserId}`, JSON.stringify(json));
    saveOnUnloadRef.current = false;
    Taro.navigateBack();
  };

  // 不保存草稿
  const cancelClickFun = () => {
    console.error('不保存了吧');
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    // 发布成功之后删除保存的草稿
    Taro.removeStorageSync(`dynamicInfo-${ucUserId}`);
    saveOnUnloadRef.current = false;
    Taro.navigateBack();
    deleteRelateCiga();
    deleteRelateCigaCabinet();
  };

  // 取消草稿
  const otherClickFun = () => {
    console.log('保存草稿哈哈哈');
    const json = getDataFun();
    Taro.setStorageSync(`dynamicInfo-${ucUserId}`, JSON.stringify(json));
    setShowSaveFlag(false);
  };

  // 当用户在弹窗中选中话题时调用
  const handleTopicSelect = (topic: any) => {
    setContentTopicList((prev: any) => {
      // 已存在则直接返回
      if (prev.some((t: any) => t.id === topic.id)) {
        showToast('该话题已添加');
        return prev;
      }
      // 超过上限
      if (prev.length >= 5) {
        showToast('最多添加 5 个话题');
        return prev;
      }
      return [...prev, topic];
    });
    setShowTopicPopup(false);
  };

  // 修改文本处理函数
  const handleContentInput = (e: any) => {
    const v = e.detail.value || '';
    const newValue = v.length > 500 ? v.slice(0, 500) : v;
    const oldValue = contentRef.current;
    // 如果是删除操作且长度差异较大，可能是光标跳跃
    if (newValue.length < oldValue.length) {
      const deletedLength = oldValue.length - newValue.length;
      // 如果一次删除超过10个字符，很可能是光标跳跃导致的
      if (deletedLength > 10) {
        // 阻止这种异常删除，恢复到上一个状态
        return;
      }
    }

    contentRef.current = newValue;
    setContent(newValue);

    //  内容变化时检查是否需要释放守护
    if (shortGuard && canReleaseGuard()) {
      setTimeout(() => {
        setShortGuard(false);
      }, 200);
    }
  };

  //  处理 Textarea 聚焦
  const handleTextareaFocus = () => {
    setTextareaFocus(true);
    // 聚焦时若满足条件则进入守护
    if (needShortGuard()) {
      setShortGuard(true);
    }
  };

  //  处理 Textarea 失焦
  const handleTextareaBlur = () => {
    setTextareaFocus(false);
  };

  //显示分割线
  const showLine = useMemo(() => {
    return (
      (contentTopicList?.length || 0) > 0 ||
      contentCigar ||
      contentCigarCabinet ||
      (contentImgUrl?.length || 0) > 0
    );
  }, [contentTopicList, contentCigar, contentCigarCabinet, contentImgUrl]);

  useEffect(() => {
    ucUserId = String(Taro.getStorageSync('userId') ?? '').trim();
    ucLoginPhone = String(Taro.getStorageSync('mobile') ?? '').trim();
    const info = Taro.getStorageSync(`dynamicInfo-${ucUserId}`);
    console.log(info, 'info===');
    if (info) {
      const json: any = JSON.parse(info);
      // 如果有保存的编写信息需要还原保持的值
      setTitle(json.title);
      setContent(json.content);
      setContentImgUrl(json.contentImgUrl);
      setContentTopicList(json.contentTopicList);
      store.publishStore.setContentCigar(json.contentCigar);
      store.publishStore.setContentCigarCabinet(json.contentCigarCabinet);

      //  恢复草稿后重新评估守护状态
      setTimeout(() => {
        if (
          json.contentImgUrl?.length > 0 ||
          (json.content?.length || 0) >= 200
        ) {
          setShortGuard(false);
        } else {
          setShortGuard(true);
        }
      }, 100);
    }

    // 退出之前删除雪茄和雪茄柜关联数据
    return () => {
      deleteRelateCiga();
      deleteRelateCigaCabinet();
    };
  }, []);

  // 监听原生事件来准确跟踪光标位置
  useEffect(() => {
    const handleSelectionChange = () => {
      const selection = window.getSelection();
      if (selection && selection.rangeCount > 0) {
        const activeElement = document.activeElement;
        if (activeElement && activeElement.tagName === 'TEXTAREA') {
          const textarea = activeElement as HTMLTextAreaElement;
          cursorPosRef.current = textarea.selectionStart || 0;
          setRealCursorPos(textarea.selectionStart || 0);
        }
      }
    };

    const handleInput = (e: Event) => {
      const target = e.target as HTMLTextAreaElement;
      if (
        target &&
        target.tagName === 'TEXTAREA' &&
        target.classList.contains('text-input')
      ) {
        const cursorPos = target.selectionStart || 0;
        cursorPosRef.current = cursorPos;
        setRealCursorPos(cursorPos);
      }
    };

    document.addEventListener('selectionchange', handleSelectionChange);
    document.addEventListener('input', handleInput, true);

    return () => {
      document.removeEventListener('selectionchange', handleSelectionChange);
      document.removeEventListener('input', handleInput, true);
    };
  }, []);

  //关联产品
  const handleRelateProduct = () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    setShowPopup(true);
  };
  //添加话题
  const handleAddTopic = () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    setShowTopicPopup(true);
  };

  return (
    <View
      className="publish-review-page"
      style={{ paddingTop: `${store.commonStore.pageAreaTop}rpx` }}
    >
      {showPhotoRecognition ? (
        <PhotoRecognition
          okClickFun={() => {}}
          showRecord={false}
          onBackClickFun={onBackClickFun}
        ></PhotoRecognition>
      ) : (
        <View className="publish-container">
          {/* 标题区 */}
          <TitleBar
            showLeftBack={true}
            title="发动态"
            onBack={backClickFun}
          ></TitleBar>
          <View className="publish-title">
            <View className="publish" onClick={handlePublish}>
              发布
            </View>
          </View>
          <AtInput
            className="title-input"
            placeholder="给动态添加一个标题吧！ (1~35 字)"
            value={title}
            name="title"
            maxLength={MAX_TITLE}
            onChange={(e: any) => setTitle(e.trim())}
          />
          <View
            className="content-area"
            style={{
              height: `calc(100vh - 210px - ${store.commonStore.pageAreaTop}rpx - ${store.commonStore.safeAreaBottom}rpx)`,
              //  关键修复：不管是否聚焦，只要可能需要输入，就始终保持足够的底部占位
              // 守护期：固定400px；非守护期：跟随键盘，最小360px
              paddingBottom: shortGuard
                ? '400px'
                : `${Math.max(keyboardHeight, 360)}px`,
            }}
          >
            <View className="text-content">
              <Textarea
                className="text-input"
                value={content}
                placeholder="点击输入正文，记录这一刻~"
                onInput={handleContentInput}
                onFocus={handleTextareaFocus}
                onBlur={handleTextareaBlur}
                autoHeight
                maxlength={-1}
                confirmType="return"
                adjustPosition={false}
              />
            </View>
            {showLine && <View className="lines"></View>}
            {contentTopicList.length > 0 && (
              <View className="topic-list">
                {contentTopicList.map((item: any, index: number) => {
                  return (
                    <View className="topic-item" key={index}>
                      <Image
                        src="https://file.linkcook.cn/image/wineMiniProgram/home/topic-delete.png"
                        className="deleteIcon"
                        onClick={() => deleteTopic(item.id)}
                      ></Image>
                      <Text>#{item.topicName}#</Text>
                    </View>
                  );
                })}
              </View>
            )}
            {contentCigar && (
              <View className="topic-container">
                <View className="relation">
                  关联雪茄：
                  <Text className="product">
                    {contentCigar.contentCigarBrand}{' '}
                    {contentCigar.contentCigarZh}
                  </Text>
                </View>
                <Image
                  src="https://file.linkcook.cn/image/wineMiniProgram/home/clear.png"
                  className="deleteRelation"
                  onClick={deleteRelateCiga}
                ></Image>
              </View>
            )}
            {contentCigarCabinet && (
              <View className="topic-container">
                <View className="relation">
                  关联雪茄柜：
                  <Text className="product">
                    {contentCigarCabinet.contentCigarCabinetZh}{' '}
                    {contentCigarCabinet.contentCigarCabinetBrand}{' '}
                    {contentCigarCabinet.model}
                  </Text>
                </View>
                <Image
                  src="https://file.linkcook.cn/image/wineMiniProgram/home/clear.png"
                  className="deleteRelation"
                  onClick={deleteRelateCigaCabinet}
                ></Image>
              </View>
            )}
            {contentImgUrl && contentImgUrl.length > 0 && (
              <View className="image-grid">
                {contentImgUrl.map((img, i) => (
                  <View className="image-cell" key={i}>
                    <Image src={img} className="cell" mode="aspectFill"></Image>
                    <Image
                      src="https://file.linkcook.cn/image/wineMiniProgram/home/deletPng.png"
                      className="delete"
                      onClick={() => removeImage(i)}
                    ></Image>
                  </View>
                ))}
              </View>
            )}
          </View>
          <Text className="char-count">
            {content.length}/{MAX_CONTENT} 字
          </Text>
          <View className="publish-buttons">
            <View onClick={handleChooseImage}>
              <View className="button-container">
                <Image
                  src="https://file.linkcook.cn/image/wineMiniProgram/home/addPicture.png"
                  className="bt-icon"
                ></Image>
              </View>
              <View className="bt-desc">添加图片</View>
            </View>
            <View onClick={() => handleRelateProduct()}>
              <View className="button-container">
                <Image
                  src="https://file.linkcook.cn/image/wineMiniProgram/home/relationPro.png"
                  className="bt-icon"
                ></Image>
              </View>
              <View className="bt-desc">关联产品</View>
            </View>
            <View
              onClick={() => {
                handleAddTopic();
              }}
            >
              <View className="button-container">
                <Image
                  src="https://file.linkcook.cn/image/wineMiniProgram/home/addTopic.png"
                  className="bt-icon"
                ></Image>
              </View>
              <View className="bt-desc">添加话题</View>
            </View>
          </View>
          <LoadingSpinner text={loadingText} />
          <StatusToast />
          <RelatePopup
            isShow={showPopup}
            onClose={() => {
              setShowPopup(false);
            }}
            takeCigaPhoto={() => {
              Taro.showToast({ title: 'AI识别开发中', icon: 'none' });
              // setShowPhotoRecognition(true);
              // setShowPopup(false);
            }}
          ></RelatePopup>
          <AddTopicPopup
            visible={showTopicPopup}
            selectedTopic={handleTopicSelect}
            onClose={() => {
              setShowTopicPopup(false);
            }}
          ></AddTopicPopup>
        </View>
      )}
      <CommonModal
        visible={showSaveFlag}
        title="是否保存当前修改？"
        okText="保存草稿"
        okClick={okClickFun}
        cancelText="不保存"
        cancelClick={cancelClickFun}
        otherText="取消"
        otherClick={otherClickFun}
      ></CommonModal>
    </View>
  );
};

export default observer(PublishComment);
